﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

using Castle.DynamicProxy;
using StructureMap;

using ProjectBase.Core;

namespace $safeprojectname$.IoC
{
    [CLSCompliant(false)]
    [Serializable]
    public class Wrapper : IInterceptor
    {
        object _lazy;
        protected readonly Type Type;

        public Wrapper(Type type)
        {
            Type = type;
        }

        public void Intercept(IInvocation invocation)
        {
            if (_lazy.IsNull()) // lazily instantiate the instance
            {
                _lazy = ProjectBase.Core.Service.Factory.CreateInstance(Type);
            }
            try
            {
                var method = invocation.Method;
                if (method.ContainsGenericParameters)
                {
                    method = method.MakeGenericMethod(invocation.GenericArguments);
                }
                invocation.ReturnValue = method.Invoke(_lazy, invocation.Arguments);
            }
            catch (TargetInvocationException ex)
            {
                PublishingManager.Publish(this, null, ex);
                throw;
            }
        }
    }
}
